package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("uploadFiles")
    @ResponseBody
//	获取到的是数组
    public Map<String, String> uploadSize4Files(@RequestParam("myFile")MultipartFile[] myFile ) {
        String filename = null;
        for (MultipartFile m : myFile) {//遍历数组
            String path = "E:\\pictures\\";
            filename = UUID.randomUUID() +".jpg";//定义存储路径
            File file = new File(path + filename);//构造file对象 把存储路径装换成file对象格式
            try {
                //通过eransferTo方法转存
                m.transferTo(file);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("Url", filename);
        return map;
    }

    @RequestMapping("uploadFile2")
    @ResponseBody
    public Map<String, String> uploadSize4Files(@RequestParam("myFile")MultipartFile myFile ) throws IOException {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String http = "https://";
        String bucketName = "1103970852";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tBHKhCvDYqndXwhvZUc";
        String accessKeySecret = "O68kFB8TSjPqnbxdFKUO5GNvmSLbfd";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写字符串。
//        String content = "Hello OSS";
        InputStream inputStream = myFile.getInputStream();
        String filename = myFile.getOriginalFilename();

        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, inputStream);

// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传字符串。
        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();

        Map<String, String> map = new HashMap<>();
        map.put("Url", http + bucketName + "." + endpoint + "/" + filename);
        System.out.println(http + bucketName + "." + endpoint + "/" + filename);
        return map;
    }


    @RequestMapping("download")
    public void download(String img, HttpServletResponse res) throws IOException {
        File file = new File("E:\\pictures\\" + img);
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream os = res.getOutputStream();
        byte[] arr = new byte[1024];
        int a;
        while((a=fis.read(arr)) != -1) {
            os.write(arr);
        }
        os.close();
        fis.close();
    }
}
